package com.uninove.tcc.bluetooth_v2;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Set;


public class Main extends ActionBarActivity {
    protected static final int DISCOVERY_REQUEST = 1;

    private BluetoothAdapter btAdapter;

    public TextView statusUpdate;
    public Button connect;
    public Button disconnect;
    public ImageView logo;
    public String toastText = "";
    public static final String EXTRA_RSSI = "android.bluetooth.device.extra.RSSI";
    private BluetoothDevice remoteDevice;

    BroadcastReceiver BluetoothState = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String stateExtra = BluetoothAdapter.EXTRA_STATE;
            int state = intent.getIntExtra(stateExtra, -1);

            switch (state){
                case(BluetoothAdapter.STATE_TURNING_ON):
                {
                    toastText="O Bluetooth está sendo ligado, aguarde...";
                    Toast.makeText(Main.this, toastText, Toast.LENGTH_SHORT).show();
                    break;
                }
                case(BluetoothAdapter.STATE_ON):
                {
                    toastText="O Bluetooth está ligado, iremos realizar uma busca, aguarde...";
                    Toast.makeText(Main.this, toastText, Toast.LENGTH_SHORT).show();
                    setupUI();
                    findDevices();
                    break;
                }
                case(BluetoothAdapter.STATE_TURNING_OFF):
                {
                    toastText="O Bluetooth está sendo desligado";
                    Toast.makeText(Main.this, toastText, Toast.LENGTH_SHORT).show();
                    break;
                }
                case(BluetoothAdapter.STATE_OFF):
                {
                    toastText="O Bluetooth está desligado";
                    Toast.makeText(Main.this, toastText, Toast.LENGTH_SHORT).show();
                    setupUI();
                    break;
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setupUI();
    }

    private void setupUI(){
        final TextView statusUpdate = (TextView) findViewById(R.id.result);
        final Button connect = (Button) findViewById(R.id.connectBtn);
        final Button disconnect = (Button) findViewById(R.id.disconnectBtn);
        final ImageView logo = (ImageView) findViewById(R.id.logo);

        disconnect.setVisibility(View.GONE);
        logo.setVisibility(View.GONE);
        btAdapter = BluetoothAdapter.getDefaultAdapter();

        if(btAdapter.isEnabled()){
            String statusText = "Seu dispositivo está pronto para fazer a busca";
            statusUpdate.setText(statusText);
            disconnect.setVisibility(View.VISIBLE);
            logo.setVisibility(View.VISIBLE);
            connect.setVisibility(View.GONE);
        }
        else{
            connect.setVisibility(View.VISIBLE);
            statusUpdate.setText("Bluetooth não está ligado");
        }
        connect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String scanModeChanged = BluetoothAdapter.ACTION_SCAN_MODE_CHANGED;
                String beDiscoverable = BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE;
                IntentFilter filter = new IntentFilter(scanModeChanged);
                registerReceiver(BluetoothState, filter);
                startActivityForResult(new Intent(beDiscoverable), DISCOVERY_REQUEST);
            }
        });

        disconnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btAdapter.disable();
                disconnect.setVisibility(View.GONE);
                logo.setVisibility(View.GONE);
                connect.setVisibility(View.VISIBLE);
                statusUpdate.setText("Bluetooth Desligado");
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        if(requestCode == DISCOVERY_REQUEST){
            Toast.makeText(Main.this,"Realizando uma busca...", Toast.LENGTH_SHORT).show();
            setupUI();
            findDevices();
        }
    }

    private void findDevices(){
        String lastUsedRemoteDevice = getLastUsedRemoteBTDevice();
        if(lastUsedRemoteDevice !=null){
            toastText = "";
            Toast.makeText(Main.this, toastText, Toast.LENGTH_SHORT).show();

            Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();
            for(BluetoothDevice pairedDevice : pairedDevices){
                if(pairedDevice.getAddress().equals(lastUsedRemoteDevice)){
                    toastText = "";
                    Toast.makeText(Main.this, toastText, Toast.LENGTH_SHORT).show();
                    remoteDevice = pairedDevice;
                }
            }
        }
        else{
            toastText = "";
            Toast.makeText(Main.this, toastText, Toast.LENGTH_SHORT).show();
        }

        if(remoteDevice == null){
            toastText = "Iniciando procura por dispositivos próximos...";
            Toast.makeText(Main.this, toastText, Toast.LENGTH_SHORT).show();

            if(btAdapter.startDiscovery()){
                toastText = "Procura iniciada, Escaneando o ambiente";
                Toast.makeText(Main.this, toastText, Toast.LENGTH_SHORT).show();
                registerReceiver(discoveryResult, new IntentFilter(BluetoothDevice.ACTION_FOUND));
            }

        }
    }

    BroadcastReceiver discoveryResult = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            BluetoothDevice remoteDevice;
            BluetoothDevice DeviceSignal;

            remoteDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            DeviceSignal = intent.getParcelableExtra(BluetoothDevice.EXTRA_RSSI);
            short intenside = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, (short)0);

            String remoteDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
            String remote = remoteDevice.getAddress();

            String carlos = "B0:D0:9C:99:5A:80";
            String alyce = "30:76:6F:65:6B:00";
            String karlla = "C0:65:99:03:D6:97";
            String flavia = "BC:47:60:5F:B3:4F";
            String pai = "";
            //Dispositivos comprados
            String white = "00:1D:AE:48:D0:77";
            String green = "00:1D:AE:49:4B:8D";
            String black = "00:1D:AE:48:8E:F3";
            String red = "00:1D:AE:49:4D:90";
            switch (remote){
                case "00:1D:AE:48:D0:77":
                    setContentView(R.layout.meninas);
                    toastText = ""+intenside;
                    Toast.makeText(Main.this, toastText, Toast.LENGTH_SHORT).show();
                    break;
                case "00:1D:AE:49:4B:8D":
                    setContentView(R.layout.pais);
                    toastText = ""+intenside;
                    Toast.makeText(Main.this, toastText, Toast.LENGTH_SHORT).show();
                    break;
                case "00:1D:AE:48:8E:F3":
                    setContentView(R.layout.sala);
                    toastText = ""+intenside;
                    Toast.makeText(Main.this, toastText, Toast.LENGTH_SHORT).show();
                    break;
                case "00:1D:AE:49:4D:90":
                    setContentView(R.layout.carlos);
                    toastText = ""+intenside;
                    Toast.makeText(Main.this, toastText, Toast.LENGTH_SHORT).show();
                    break;
            }
            btAdapter.startDiscovery();
            registerReceiver(discoveryResult, new IntentFilter(BluetoothDevice.ACTION_FOUND));
            /*
            switch(remoteDeviceName){
                case "ALEX-PC":
                    setContentView(R.layout.note_acer);
                    break;
                case "LG":
                    setContentView(R.layout.note_lg);
                    break;
                case "Alex":
                    setContentView(R.layout.cell_motorola);
                    break;
                /*case "BQ-618":
                    setContentView(R.layout.headphone);
                    break;
                //Cozinha
                //case "F":
                    setContentView(R.layout.note_acer);
                    break;
                //Sala
                //case "Karlla":
                    setContentView(R.layout.note_lg);
                    break;
                //Garagem
                case "Francisco":
                    setContentView(R.layout.cell_motorola);
                    break;
                //Fundos
                case "Alyce":
                    setContentView(R.layout.headphone);
                    break;*/
                /*default:
                    toastText = ""+remoteDevice;
                    //white
                    if (toastText == "00:1D:AE:48:D0:77"){
                        setContentView(R.layout.meninas);
                    }
                    //green
                    else if(toastText == "00:1D:AE:49:4B:8D"){
                        setContentView(R.layout.pais);
                    }
                    //black
                    else if(toastText == "00:1D:AE:48:8E:F3"){
                        setContentView(R.layout.sala);
                    }
                    //red
                    else
                        setContentView(R.layout.carlos);
                    break;
            }*/

        }
    };

    private String getLastUsedRemoteBTDevice(){
        SharedPreferences prefs = getPreferences(MODE_PRIVATE);
        String result = prefs.getString("LAST_REMOTE_DEVICE_ADDRESS", null);
        return null;
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent main in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}